package com.github.tetrisgame.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.github.tetrisgame.R;
import com.github.tetrisgame.databinding.ActivityVerifyBinding;
import com.github.tetrisgame.utils.Communication;

import java.util.Timer;
import java.util.TimerTask;

import cn.bmob.v3.BmobSMS;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;

public class verifyActivity extends AppCompatActivity {
    ActivityVerifyBinding activityVerifyBinding;
    private int time = 60;
    Timer timer = new Timer();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        activityVerifyBinding = ActivityVerifyBinding.inflate(getLayoutInflater());
        setContentView(activityVerifyBinding.getRoot());
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        Intent intent = getIntent();
        String phone = intent.getStringExtra("phone");

        activityVerifyBinding.verifyView.setOnGetPasswordListener(code->{
            equal(phone,code);
        });
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                if(time > 0){
                    time--;
                    runOnUiThread(()->{
                        activityVerifyBinding.button2.setText(time + "后可重新发送验证码");
                    });
                    return;
                }
                activityVerifyBinding.button2.setText("发送验证码");


            }
        };
        timer.schedule(timerTask,0,1000);
        activityVerifyBinding.button2.setOnClickListener(v->{
            if(time == 0){
                time = 60;

            }
        });
    }
    private void equal(String phone,String code){

        BmobSMS.verifySmsCode(phone, code, new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Toast.makeText(verifyActivity.this,"绑定手机号码成功",Toast.LENGTH_LONG).show();
                    Intent mainIntent = new Intent(verifyActivity.this,MainActivity.class);
                    startActivity(mainIntent);
                } else {
                    Toast.makeText(verifyActivity.this,"绑定手机号码失败：" + e.getErrorCode() + "-" + e.getMessage(),Toast.LENGTH_LONG).show();
                }
            }
        });
    }




}